<style scoped>
.footer {
  background-color: white;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.footer-content {
  height: 100%;
  margin-left: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.a-left {
  display: flex;
  align-items: center;
  margin-left: 2%;
  text-decoration: none;
  color: black
}

.a-right {
  margin-left: 2%;
  text-decoration: none;
  color: black
}

.a-right:hover,
.a-left:hover {
  color: blue;
}
</style>

<template>
  <!--  <div style="position: fixed; z-index: -1; width: 100%; height: 100%">-->
  <!--    <video autoplay loop muted style="width: 100%; height: 100%; object-fit: cover;">-->
  <!--      <source src="../assets/mp4/login.mp4" type="video/mp4">-->
  <!--    </video>-->
  <!--  </div>-->
  <!--  background-color: #001529;-->
  <div style="display: flex;height: 100vh;align-items: center;justify-content: center;">
    <div style="  display: flex;width: 50%;height: 60vh;border-radius: 5px;background-color: white;overflow: hidden;">
      <!-- 图片 -->
      <div style="flex: 1;display: flex;justify-content: center;align-items: center;">
        <img style="width: 100%;" src="../assets/img/register.png" alt="">
      </div>
      <!-- 表单 -->
      <div style="display: flex;flex-direction: column;  flex: 1;justify-content: center;align-items: center;">
        <div style="width: 100%;font-size: 20px;font-weight: bold;text-align: center;margin-top: 35px">欢迎注册招投标文件管理系统
        </div>
        <el-form :model="data.user" style="height: 75%;width: 80%;padding-top: 10px;box-sizing: border-box"
                 @keyup.enter="clickRegister"
                 :rules="data.rules"
                 ref="ruleFormRef">
          <el-form-item prop="username">
            <el-input size="large" :prefix-icon="Avatar" placeholder="请输入账号" v-model="data.user.username"></el-input>
          </el-form-item>

          <el-form-item prop="password">
            <el-input size="large" :prefix-icon="Lock" show-password placeholder="请输入密码"
                      v-model="data.user.password"></el-input>
          </el-form-item>

          <el-form-item prop="ConfirmPassword">
            <el-input size="large" :prefix-icon="Lock" show-password placeholder="请再次输入密码"
                      v-model="data.user.ConfirmPassword"></el-input>
          </el-form-item>

          <el-form-item prop="InputValidCode">
            <el-input style="flex: 1;" size="large" :prefix-icon="CircleCheck" placeholder="请输入验证码"
                      v-model="data.user.InputValidCode"></el-input>
            <div style="flex: 1;">
              <ValidCode @input="getValidCode"/>
            </div>
          </el-form-item>

          <el-form-item class="mb-2 flex items-center text-sm">
            <div style="display: flex;justify-content: center;width: 100%">
              <el-radio-group v-model="data.user.business" class="ml-4">
                <el-radio label="1" size="large" style="flex: 1">投标业务</el-radio>
                <el-radio label="2" size="large" style="flex: 1">招标业务</el-radio>
              </el-radio-group>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button type="primary"
                       :disabled="!isFormValid"
                       style="width: 100%;"
                       @click="clickRegister">注 册</el-button>
          </el-form-item>
        </el-form>

        <div style="display: flex;margin:15px 0 15px 0;width: 76%;box-sizing: border-box">
          <div>已有账号？请 <span style="flex: 1;color: #409eff;cursor: pointer;" @click="$router.push('/login')">登录</span></div>
        </div>

      </div>
    </div>
  </div>
  <el-footer class="footer">
    <div class="footer-content">
      <span>©2024 ldystudy.cn 版权所有</span>
      <a target="_blank" class="a-left"
         href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=52262202000037">
        <img src="/备案图标.png" style="float:left;height: 50%;"/>
        <p>
          贵公网安备 52262202000037号
        </p>
      </a>
      <a class="a-right" href="https://beian.miit.gov.cn" target="_blank">工信部备案：黔ICP备2023009910号</a>
    </div>
  </el-footer>
</template>

<script setup>
import ValidCode from "@/components/ValidCode.vue";
import {nextTick, reactive, ref, watch} from 'vue';
import {Avatar, CircleCheck, Lock} from '@element-plus/icons-vue';
import request from "@/utils/request.js";
import {ElMessage} from "element-plus";

import {useRouter} from "vue-router";

const router = useRouter();

const ruleFormRef = ref(null);
// 定义一个响应式的data属性来存储整个表单所有字段的有效性状态
const isFormValid = ref(false);

// 监听表单中的每个输入字段，一旦有变化就进行验证
const updateFormValidity = () => {
  if (ruleFormRef.value) {
    ruleFormRef.value.validate((valid) => {
      isFormValid.value = valid; // 根据验证结果更新表单状态
    });
  }
};




// 定义一个自定义验证器来检查确认密码是否与密码匹配
const validateConfirmPassword = (rule, value, callback) => {
  if (value !== data.user.password) {
    callback(new Error("两次密码输入不一致"));
  } else {
    callback();
  }
};

const data = reactive({
  user: {
    username: '',
    password: '',
    ConfirmPassword: '',
    InputValidCode: '',
    business: "1",
  },
  rules: {
    username: [
      {required: true, message: "请输入账号", trigger: "blur"},
      {min: 8, max: 20, message: "账号长度为[8-20]", trigger: "blur"},
      {pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,20}$/, message: "账号必须同时含有大小写字母和数字", trigger: "blur"}
    ],
    password: [
      {required: true, message: "请输入密码", trigger: "blur"},
      {min: 8, max: 20, message: "密码长度为[8-20]", trigger: "blur"},
      {pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,20}$/, message: "密码必须同时含有大小写字母和数字", trigger: "blur"}
    ],
    ConfirmPassword: [
      {required: true, message: "请输入确认的密码", trigger: "blur"},
      {min: 8, max: 20, message: "密码长度为[8-20]", trigger: "blur"},
      // 这里需要一个验证器来确认两次密码是否相同
      {validator: validateConfirmPassword, trigger: "blur"} // 自定义验证器
    ],
    InputValidCode: [ // 验证码的校验规则
      {required: true, message: "请输入验证码", trigger: "blur"},
      {
        validator: (rule, value, callback) => {
          if (value.toLowerCase() !== data.validCode.toLowerCase()) {
            callback(new Error('验证码错误'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ],
  },
  validCode: '', // 系统生成的验证码
});

// 每当数据.user对象的一部分发生改变时调用updateFormValidity
watch(() => data.user, updateFormValidity, { deep: true });

// 查询账户是否已存在
const checkUsername = () => {
  return new Promise((resolve, reject) => {
    request.get(`/user/queryUsername/${data.user.username}`).then((res) => {
      resolve(!!res.data);
    }).catch((error) => {
      reject(error);
    });
  });
};


// 点击注册按钮进行表单验证和注册
const clickRegister = async () => {
  try {
    const isUsernameExists = await checkUsername();
    if (!isUsernameExists) {
      const registerData = {
        username: data.user.username,
        password: data.user.password,
        roles: data.user.business,
      };
      if (data.user.password === data.user.ConfirmPassword && data.user.InputValidCode === data.validCode) {
        request.post(`/user/register`, registerData).then((res) => {
          if (res.code === 200) {
            ElMessage.info(res.data);
            router.push('/login');
          } else {
            ElMessage.error(res.data);
          }
        });
      } else {
        ElMessage.error("输入错误，请重新输入！");
      }
    } else {
      ElMessage.error("该用户已存在，请重新注册！");
      //刷新页面
      window.location.reload();
    }
  } catch (error) {
    console.error("Error checking username:", error);
    ElMessage.error("查询用户失败，请稍后重试！");
  }
};


// 从ValidCode组件中获取验证码
const getValidCode = (code) => {
  data.validCode = code;
};


// 在setup函数之后，确保初始加载时表单状态为非有效
nextTick(() => {
  updateFormValidity();
});

</script>
